from BitTorrent.bencode import bencode,bdecode
from BitTorrent.download import download,defaults
from BitTorrent.fmt import fmttime, fmtsize
from threading import Thread, Event, Lock
from sys import stdout
from os.path import abspath, join, exists, getsize
from time import sleep


filecheck=Lock()


class StatusUpdater:
    def __init__(self, id, params,output=[],threads={},save_path='',torrents={}):
        self.torrents=torrents
        self.torrent=self.torrents[id]
        self.output=output
        self.id=id
        self.output[id]=[]
        self.params = params
        self.myinfo = threads[self.id]
        self.done = 0
        self.checking = 0
        self.activity = 'starting'
##        self.display()
        self.myinfo['errors'] = []
        self.metafile=bdecode(open(self.torrents[self.id]['path'],'rb').read())
        #trim pieces data
        del self.metafile['info']['pieces']
        print "self.output=",self.output

    def download(self): 
##        print self.metafile
        download(self.params + ['--responsefile', self.torrent['path']], self.choose, self.display, self.finished, self.err, self.myinfo['kill'], 80)
##        download(self.params, self.choose, self.display, self.finished, self.err, self.myinfo['kill'], 80)
        print 'Torrent %s stopped' % self.id
        stdout.flush()

    def finished(self): 
        self.done = 1
        self.myinfo['done'] = 1
        self.activity = 'complete'
        self.display({'fractionDone' : 1, 'downRate' : 0})

    def err(self, msg): 
        self.myinfo['errors'].append(msg)
        self.display()

    def failed(self): 
        self.activity = 'failed' 
        self.display() 

##    def choose(self, default, size, saveas, dir):
##        global filecheck
##        self.myinfo['downfile'] = default
##        self.myinfo['filesize'] = fmtsize(size)
##        if saveas == '': 
##            saveas = default
##        # it asks me where I want to save it before checking the file.. 
##        if exists(self.id[:-len(ext)]) and (getsize(self.id[:-len(ext)]) > 0):
##            # file will get checked
##            while (not filecheck.acquire(0) and not self.myinfo['kill'].isSet()):
##                self.myinfo['status'] = 'disk wait'
##                sleep(0.1)
##            if not self.myinfo['kill'].isSet():
##                self.checking = 1
##                self.myinfo['checking'] = 1
##        self.myinfo['savefile'] = self.file[:-len(ext)]
##        return self.file[:-len(ext)]
    def choose(self,default,size,saveas,dir):
        global filecheck
        print "choose default=",default,"size=",size,"saveas=",saveas,"dir=",dir
        self.myinfo['downfile'] = default
        self.myinfo['filesize'] = fmtsize(size)
        #full path to file
        save_path = self.torrent['save_path']+'/'+default
        if exists(save_path) and (getsize(save_path) > 0):
            print "CHECKING"
            while (not filecheck.acquire(0) and not self.myinfo['kill'].isSet()):
                print "disk wait"
                self.myinfo['status'] = 'disk wait'
                sleep(0.1)
            if not self.myinfo['kill'].isSet():
                print 'SET CHECKING TO 1'
                self.checking=1
                self.myinfo['checking']=1
        self.myinfo['savefile']=save_path
        return save_path
    
    def display(self, dict = {}):
        fractionDone = dict.get('fractionDone', None)
        timeEst = dict.get('timeEst', None)
        activity = dict.get('activity', None) 
        global status
        if activity is not None and not self.done: 
            if activity == 'checking existing file':
                self.activity = 'disk check'
            elif activity == 'connecting to peers':
                self.activity = 'connecting'
            else:
                self.activity = activity
        elif timeEst is not None: 
            self.activity = fmttime(timeEst, 1)
        if fractionDone is not None: 
            self.myinfo['status'] = '%s %.0f%%' % (self.activity, fractionDone * 100)
        else:
            self.myinfo['status'] = self.activity
        if self.activity != 'checking existing file' and self.checking:
            # we finished checking our files. 
            filecheck.release()
            self.checking = 0
            self.myinfo['checking'] = 0
        if dict.has_key('upRate'):
            self.myinfo['uprate'] = dict['upRate']
        if dict.has_key('downRate'):
            self.myinfo['downrate'] = dict['downRate']
        if dict.has_key('upTotal'):
            self.myinfo['uptotal'] = dict['upTotal']
        if dict.has_key('downTotal'):
            self.myinfo['downtotal'] = dict['downTotal']
##        print "display=",self.myinfo
